package com.lxl.chat.aspect;

import com.lxl.chat.util.IMoocJSONResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * http切面
 *
 * @date & @author: 2019/1/18 9:01 & lxl
 */
@Slf4j
@Aspect
@Component
public class HttpAspect {

    @Pointcut("execution(public * com.lxl.chat.*.web.*.*(..))")
    public void log() {
    }

    @Around("execution(public * com.lxl.chat.controller.*.*(..)) && args(.., bindingResult)")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint, BindingResult bindingResult) throws Throwable {
        Object retVal;
        if (bindingResult.hasErrors()) {
            HashMap<String, Object> errorMap = new HashMap<>(16);
            bindingResult.getAllErrors().forEach(error -> {
                FieldError fieldError = (FieldError) error;
                errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
                log.error("错误字段: {} -> 错误信息: {}", fieldError.getField(), fieldError.getDefaultMessage());
            });
            retVal = new IMoocJSONResult(1111, "出错", "未知错误");
        } else {
            retVal = proceedingJoinPoint.proceed();
        }
        return retVal;
    }

    @Before("log()")
    public void doBefore() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();
        log.info("请求来自: {}", request.getRemoteAddr());
    }
}
